from flask import Blueprint,render_template,session,jsonify,request,send_file
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity
from ..models.User import User
from ..models.Op import Op
from ..models.Originimage import Originimage
from ..models.Afteropimage import Afteropimage
from exts import db
import  os

history = Blueprint('history',__name__)


@history.route('/history')
@jwt_required()
def history_get():
    #token解码
    username=get_jwt_identity()
    user = User.query.filter_by(userName=username).first()
    userId=user.userId

    # Op模型中有一个外键 userId 关联到 User 模型的 userId,originImageId关联originimage的imageId
    ops = Op.query.filter_by(userId=user.userId).all()
    op_list=[]
    for op in ops:
        # 查询每个操作记录对应的原始图片信息
        origin_image = Originimage.query.filter_by(imageId=op.originImageId).first()
        # 查询每个操作记录对应的处理后图片信息
        after_op_image = Afteropimage.query.filter_by(id=op.afterOpImageId).first()
        # 构造操作记录与原始图片信息的字典
        op_dict = {
            'opId': op.opId,
            'userId': op.userId,
            'originImageId': op.originImageId,
            'afterOpImageId': op.afterOpImageId,
            'originImageInfo': {
                'imageId': origin_image.imageId,
                'imageName': origin_image.imageName,
                'imageType': origin_image.imageType,
                'imagePath': origin_image.imagePath,
                'uploadTime': origin_image.uploadTime,
            },
            'afterOpImageInfo':{
                'id': after_op_image.id,
                'imageName': after_op_image.imageName,
                'imagePath': after_op_image.imagePath,
                'createTime': after_op_image.createtime,
                'imageType': after_op_image.imageType,
            }
        }
        op_list.append(op_dict)
    print(op_list)
    print(op_list[0]['afterOpImageInfo']['createTime'])
    print(op_list[0]['originImageInfo']['uploadTime'])
    return jsonify({'ops': op_list})

@history.route('/history/delete', methods=['POST'])
@jwt_required()
def history_delete():
    # 解码 token 并获取用户名
    username = get_jwt_identity()
    user = User.query.filter_by(userName=username).first()
    userId = user.userId

    # 从请求的 JSON 数据中获取要删除的操作记录 ID
    data = request.get_json()
    op_id = data.get('opId')

    if not op_id:
        return jsonify({'message': 'Missing opId in request'}), 400

    # 查询要删除的操作记录
    op = Op.query.filter_by(opId=op_id, userId=userId).first()

    if not op:
        return jsonify({'message': 'Operation record not found'}), 404

    # 查询操作记录对应的原始图片和处理后图片信息
    origin_image = Originimage.query.filter_by(imageId=op.originImageId).first()
    after_op_image = Afteropimage.query.filter_by(id=op.afterOpImageId).first()

    # 删除操作记录
    db.session.delete(op)

    # 如果需要，也可以删除相关的原始图片和处理后图片信息
    if origin_image:
        db.session.delete(origin_image)
    if after_op_image:
        db.session.delete(after_op_image)

    # 提交事务
    db.session.commit()

    return jsonify({'message': 'Operation record and related images deleted successfully'}), 200


@history.route('/download_processed/<filename>')
def download_processed_file(filename):
    # 设定处理后图片的静态文件目录
    static_folder = 'static/processed'
    # 拼接文件路径
    file_path = os.path.join(static_folder, filename)

    return send_file(file_path, as_attachment=True, download_name=filename)


@history.route('/download_origin/<filename>')
def download_origin_file(filename):
    # 设定原始图片的静态文件目录
    static_folder = 'static/uploads'
    # 拼接文件路径
    file_path = os.path.join(static_folder, filename)

    return send_file(file_path, as_attachment=True, download_name=filename)